import React, { ReactElement, useContext, useEffect, useRef } from 'react';
import { View, ScrollView } from 'react-native';
import moment from 'moment';
import Spu from '../Spu';

import styles from './style';
import { Store } from '../../reducer';
import Empty from '../../../../../../components/Empty';
import CustomText from '../../../../../../components/Text';
import Calender from '../Calender';
import { setScroll } from '../../actions';
import CurrentLesson from '../CurrentLesson';

export default (): ReactElement => {
  const scroll = useRef<ScrollView>(null);

  const { state } = useContext(Store);
  const { data, currentDate } = state;
  const { courses = [], lessons = [] } = data;

  const toDayLessons = lessons.filter(
    (lesson): boolean =>
      moment(lesson.startTime).format('YYYY-MM-DD') === currentDate.date
  );

  useEffect((): void => {
    setScroll(scroll);
  }, []);

  return (
    <View style={styles.container}>
      <CustomText style={styles.title}>我的课程</CustomText>
      <Calender />
      <ScrollView ref={scroll}>
        {toDayLessons.map(
          (lesson): ReactElement => (
            <CurrentLesson key={lesson.id} {...lesson} />
          )
        )}
        {courses.length > 0 ? (
          <View style={styles.content}>
            <CustomText style={styles.type}>正在学习</CustomText>
            {courses.map(
              (item): ReactElement => (
                <Spu key={item.id} {...item} />
              )
            )}
          </View>
        ) : (
          <Empty emptyDesc="暂无购买课程" style={styles.empty} />
        )}
      </ScrollView>
    </View>
  );
};
